package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class MovementsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PicUploadService picUploadService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    /**
     * 保存动态信息
     *
     * @param textContent
     * @param location
     * @param longitude
     * @param latitude
     * @param imageContent
     * @return
     */
    public String saveMovements(String textContent, String location, String longitude, String latitude, MultipartFile[] imageContent) {
        //获取user
        User user = UserThreadLocal.get();
        if (null == user) {
            return null;
        }

        //填充数据
        Publish publish = new Publish();
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLongitude(longitude);
        publish.setLatitude(latitude);
        publish.setUserId(user.getId());

        List<String> medias = new ArrayList<>();

        //将2进制图片上传至阿里云，返回对应的文件名，并填充
        for (MultipartFile multipartFile : imageContent) {
            PicUploadResult uploadResult = picUploadService.upload(multipartFile);
            String name = uploadResult.getName();
            medias.add(name);
        }
        publish.setMedias(medias);

        //调用dubbo保存数据
        return this.quanZiApi.savePublish(publish);
    }

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 查询好友动态
     *
     * @param user
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryPublishList(User user, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        Long userId = null;

        PageInfo<Publish> pageInfo = null;
        if (null == user) { //推荐动态逻辑处理
            // 查询Redis todo
            String value = this.redisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId());
            //100018,100049,100029,100048,100023,100091
            //如果不为空则分隔
            if (StringUtils.isNotEmpty(value)) {
                String[] splits = value.split(",");

            //由于有分页参数，那么我们要计算起始索引，和终止索引
            Integer startIndex = (page - 1) * pageSize;

            //startIndex是否有可能越界
            if(startIndex < splits.length) {
                //endIndex = page * pageSize - 1
                Integer endIndex = page * pageSize - 1;

                //endIndex可不可能越界
                if(endIndex >= splits.length) {
                    //如果越界，我们该怎么办，
                    endIndex = splits.length -1;
                }


            //获取数组中的pid
            List<Long> pidList = new ArrayList<>();

            //startIndex  endIndex   split.length
                for (int i = startIndex; i <= endIndex; i++) {
                    pidList.add(Long.valueOf(splits[i]));
                }

                List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                pageInfo = new PageInfo<>();
                pageInfo.setRecords(publishList);
            }
            }
        }

        //如果上面的数据没有查询出来，我们就去查默认推荐的数据
        if (null == pageInfo) {
            if (user != null) {
                userId = user.getId();
            }
            pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        }


        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        pageResult.setCounts(0);
        pageResult.setPages(0);

        List<Publish> records = pageInfo.getRecords();

        if (CollectionUtils.isEmpty(records)) {
            //没有动态信息
            return pageResult;
        }

        if (CollectionUtils.isEmpty(records)) {
            // 没有查询到动态数据
            return pageResult;
        }

        pageResult.setItems(this.getMovements(records));

        return pageResult;

    }

    /**
     * 点赞和喜欢判断
     *
     * @param records
     * @return
     */
    private List<Movements> getMovements(List<Publish> records) {
        //循环发布列表，并且往里面填充，其他的动态数据，如是否喜欢。是否点赞
        List<Movements> movementsList = new ArrayList<>();

        //获取好友id的集合数据
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setUserId(record.getUserId());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

//            UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(record.getUserId());
//            movements.setAge(userInfo.getAge());
//            movements.setAvatar(userInfo.getLogo());
//            movements.setGender(userInfo.getSex().name().toLowerCase());
//            movements.setNickname(userInfo.getNickName());
//            movements.setTags(StringUtils.split(userInfo.getTags(), ','));

            movements.setCommentCount(10); //TODO 评论数
            movements.setDistance("1.2公里"); //TODO 距离


            String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + record.getId().toHexString();
            movements.setHasLiked(this.redisTemplate.hasKey(likeUserCommentKey) ? 1 : 0); //TODO 是否点赞（1是，0否）

            String likeCommentKey = "QUANZI_COMMENT_LIKE_" + record.getId().toHexString();
            String data = this.redisTemplate.opsForValue().get(likeCommentKey);
            if (StringUtils.isNotEmpty(data)) {
                movements.setLikeCount(Integer.valueOf(data)); //TODO 点赞数
            } else {
                movements.setLikeCount(0);
            }


            String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + movements.getId();
            movements.setHasLoved(this.redisTemplate.hasKey(loveUserCommentKey) ? 1 : 0); //是否喜欢

            String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveValue = this.redisTemplate.opsForValue().get(loveCommentKey);
            if (StringUtils.isNotEmpty(loveValue)) {
                movements.setLoveCount(Integer.valueOf(loveValue)); //喜欢数
            } else {
                movements.setLoveCount(0); //喜欢数
            }

            movementsList.add(movements);

            userIds.add(movements.getUserId());
        }


        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));

                    break;
                }
            }
        }
        return movementsList;
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null, page, pageSize);
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 点赞
     * @param publishId
     * @return
     */
    public Long likeComment(String publishId) {
        //直接调用dubbo，进行点赞操作,返回值是false则直接返回null
        boolean b = this.quanZiApi.saveLikeComment(UserThreadLocal.get().getId(), publishId);

        //保存失败直接返回null
        if (b != true) {
            return null;
        }

        //如果redis里面没有这个key，去查询dubbo，获取点赞数
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long likeCount = 0L;
        if (!this.redisTemplate.hasKey(likeCommentKey)) {
            likeCount = this.quanZiApi.queryCommentCount(publishId, 1);
            this.redisTemplate.opsForValue().set(likeCommentKey, String.valueOf(likeCount));
        } else {
            //往redis里面存当前用户点赞信息，以及点赞数+1
            likeCount = this.redisTemplate.opsForValue().increment(likeCommentKey);
        }

        // 记录当前用于已经点赞 走到这里就说明他一定没有点过赞，直接保存
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey, "1");

        return likeCount;
    }


    /**
     * 取消点赞
     * @param publishId
     * @return
     */
    public Long disLikeComment(String publishId) {
        //remove type=1
        boolean b = this.quanZiApi.removeComment(UserThreadLocal.get().getId(), publishId, 1);

        //删除失败
        if (!b) {
            return null;
        }

        // redis中的点赞数需要减少1
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommentKey);

        // 删除该用户的标记点赞
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommentKey);

        return count;
    }

    /**
     * 喜欢
     * @param publishId
     * @return
     */
    public Long loveComment(String publishId) {
        boolean b = this.quanZiApi.saveLoveComment(UserThreadLocal.get().getId(), publishId);

        if (!b) {
            return null;
        }
        // 保存成功，获取喜欢数
        Long loveCount = 0L;
        String likeCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        if (this.redisTemplate.hasKey(likeCommentKey)) {
            loveCount = this.quanZiApi.queryCommentCount(publishId, 3);
            this.redisTemplate.opsForValue().set(likeCommentKey, String.valueOf(loveCount));
        } else {
            loveCount = this.redisTemplate.opsForValue().increment(likeCommentKey);
        }

        // 记录当前用于已经喜欢
        String likeUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey, "3");

        return loveCount;
    }

    /**
     * 取消喜欢
     * @param publishId
     * @return
     */
    public Long unLoveComment(String publishId) {
        //remove type=1
        boolean b = this.quanZiApi.removeComment(UserThreadLocal.get().getId(), publishId, 3);

        //删除失败
        if (!b) {
            return null;
        }

        // redis中的点赞数需要减少1
        String likeCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long unLoveCount = this.redisTemplate.opsForValue().decrement(likeCommentKey, 3);

        // 删除该用户的标记点赞
        String likeUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommentKey);

        return unLoveCount;
    }

    /**
     * 通过id查找动态
     * @param publishId
     * @return
     */
    public Movements queryMovementsById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (null == publish) {
            return null;
        }

        //查询到动态数据，数据的填充
        List<Movements> movementsList = this.fillValueToMovements(Arrays.asList(publish));
        return movementsList.get(0);
    }

    /**
     * 抽取的方法,填充动态信息
     * @param records
     * @return
     */
    private List<Movements> fillValueToMovements(List<Publish> records) {
        User user = UserThreadLocal.get();
        List<Movements> movementsList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());

            if (!userIds.contains(record.getUserId())) {
                userIds.add(record.getUserId());
            }

            String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLiked(this.redisTemplate.hasKey(likeUserCommentKey) ? 1 : 0); //是否点赞

            String likeCommentKey = "QUANZI_COMMENT_LIKE_" + movements.getId();
            String value = this.redisTemplate.opsForValue().get(likeCommentKey);
            if (StringUtils.isNotEmpty(value)) {
                movements.setLikeCount(Integer.valueOf(value)); //点赞数
            } else {
                movements.setLikeCount(0); //点赞数
            }

            String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLoved(this.redisTemplate.hasKey(loveUserCommentKey) ? 1 : 0); //是否喜欢

            String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveValue = this.redisTemplate.opsForValue().get(loveCommentKey);
            if (StringUtils.isNotEmpty(loveValue)) {
                movements.setLoveCount(Integer.valueOf(loveValue)); //喜欢数
            } else {
                movements.setLoveCount(0); //喜欢数
            }

            movements.setDistance("1.2公里"); //TODO 距离
            movements.setCommentCount(30); //TODO 评论数
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated()))); //发布时间，10分钟前
            movements.setTextContent(record.getText());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));

            movementsList.add(movements);
        }


        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userInfoQueryWrapper);

        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {

                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));
                    movements.setNickname(userInfo.getNickName());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setAge(userInfo.getAge());

                    break;
                }
            }
        }

        return movementsList;
    }


    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    /**
     * 查看访客列表
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        String redisKey = "visitor_date_" + user.getId();

        //如果redis中存在上次查询的时间,就按照这个时间之后查询,如果没有就查询前5个
        List<Visitors> visitors = null;
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (StringUtils.isEmpty(value)){
            visitors = this.visitorsApi.topVisitor(user.getId(), 5);
        }else {
            visitors = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(value));
        }

        if(CollectionUtils.isEmpty(visitors)){
            return Collections.emptyList();
        }

        List<Long> userIds = new ArrayList<>();
        for (Visitors visitor : visitors) {
            userIds.add(visitor.getVisitorUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfoList) {
                if (visitor.getVisitorUserId().longValue() == userInfo.getUserId().longValue()){
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(),","));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }

    /**
     * 查询自己的全部动态
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId,page,pageSize);

        List<Publish> records = albumPageInfo.getRecords();

        if (CollectionUtils.isEmpty(records)){
            return pageResult;
        }

        pageResult.setItems(this.fillValueToMovements(records));

        return pageResult;

    }
}
